﻿using System.Threading.Channels;

namespace App.Channels
{
    /// <summary>
    /// 队列
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ChannelMsg<T> : IChannelMsg<T>
    {
        private readonly Channel<T> _channel;
        public ChannelMsg()
        {
            _channel = Channel.CreateUnbounded<T>();
        }

        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="reqDto"></param>
        /// <returns></returns>
        public async Task WriteAsync(T reqDto, bool isNoWrite = false)
        {
            await _channel.Writer.WriteAsync(reqDto);

            if (isNoWrite)
            {
                _channel.Writer.Complete();
            }
        }

        /// <summary>
        /// 读取
        /// </summary>
        /// <returns></returns>
        public async Task ReadAsync(Action<T> func)
        {
            while (await _channel.Reader.WaitToReadAsync())
            {
                while (_channel.Reader.TryRead(out T result))
                {
                    if (result == null)
                    {
                        continue;
                    }

                    func.Invoke(result);
                }
            }
        }
    }

}
